package cn.bincker.mycaptcha.slider;

import cn.bincker.mycaptcha.basic.AnswerStorage;
import cn.bincker.mycaptcha.basic.CaptchaGuard;
import cn.bincker.mycaptcha.basic.impl.DefaultCaptchaBackgroundCutter;
import cn.bincker.mycaptcha.basic.impl.DefaultCaptchaGuard;
import cn.bincker.mycaptcha.basic.impl.DefaultCaptchaServiceImpl;
import cn.bincker.mycaptcha.basic.impl.SessionAnswerStorage;
import cn.bincker.mycaptcha.slider.controller.SliderCaptchaController;
import cn.bincker.mycaptcha.slider.entity.SliderAnswer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@SuppressWarnings("SpringFacetCodeInspection")
@Configuration
@ConditionalOnProperty(value = "my-captcha.slider.enabled", havingValue = "true")
@EnableConfigurationProperties(SliderCaptchaProperties.class)
public class SliderCaptchaConfiguration{
    /**
     * 答案存储器
     */
    @Bean
    public AnswerStorage<SliderAnswer> getAnswerStorage(SliderCaptchaProperties properties){
        return new SessionAnswerStorage<>(properties) {
            @Override
            public String getName() {
                return "SLIDER";
            }
        };
    }

    /**
     * Controller
     */
    @Bean
    public SliderCaptchaController controller(SliderCaptchaProperties properties, AnswerStorage<SliderAnswer> answerStorage){
        var captchaBackgroundCutter = new DefaultCaptchaBackgroundCutter(properties);
        var cacheManager = new SliderCacheManagerImpl(properties);
        cacheManager.reload();
        var captchaFactory = new SliderCaptchaFactory(properties, captchaBackgroundCutter, cacheManager);
        var sliderCaptchaService =  new DefaultCaptchaServiceImpl<>(captchaFactory, cacheManager, answerStorage);
        return new SliderCaptchaController(properties, sliderCaptchaService);
    }

    /**
     * 守卫
     */
    @Bean
    public CaptchaGuard captchaGuard(SliderCaptchaProperties properties, AnswerStorage<SliderAnswer> answerStorage){
        var verifyRequestAnswerResolver =  new SliderVerifyRequestAnswerResolver();
        var captchaVerifier = new SliderCaptchaVerifier(verifyRequestAnswerResolver, answerStorage, properties);
        return new DefaultCaptchaGuard(properties, captchaVerifier);
    }
}
